/*
 * @Date: 2023-12-18 17:56:34
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-04-19 20:40:10
 * @FilePath: \server\src\server\app\MysqlUtils.h
 */
#ifndef MYSQLUTILS_H
#define MYSQLUTILS_H
#pragma once

// boost 库
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/core/ref.hpp>
#include <boost/mysql.hpp>
#include <boost/system/detail/error_code.hpp>

// protobuf
#include <data/GroupInfo.pb.h>
#include <data/Message.pb.h>
#include <data/UserInfo.pb.h>

// std
#include <string>
#include <vector>

using namespace proto;

class MysqlUtils {
protected:
    static boost::asio::ssl::context ssl_ctx;
    static boost::mysql::tcp_ssl_connection* mysqlconn;
    std::string last_error;
    static bool stop;

public:
    MysqlUtils(){};

protected:
    static void ping_loop(boost::asio::io_context& ctx, boost::shared_ptr<boost::asio::steady_timer> timer);
    void do_exception(boost::mysql::error_with_diagnostics& e, std::string func = "");
    void do_exception(const std::exception& e, std::string func = "");
public:
    std::string lastError();

    static void start_ping(boost::asio::io_context& ctx);
    static bool connect();
    static bool reconnect();
    bool getAcount(data::Account& account);
    bool getUserInfo(std::string userId, data::UserInfo& user);
    bool setUserInfo(const data::UserInfo& user);
    bool setAcount(const data::Account& account);
    int getFriends(std::string myuserId, std::vector<data::FriendInfo>& users);
    bool getFriendInfo(std::string myuserId, std::string friendsId, data::FriendInfo& info);
    bool createRoom(data::ChatRoomInfo &info);
    bool addRoomMember(std::string roomid, std::string userid);
    bool delRoomMember(std::string roomid, std::string userid);
    int getRoomsMembers(std::string roomId, std::vector<data::UserInfo>& users);
    int getAllUsers(std::vector<data::UserInfo>& users);
    int getRooms(std::string myuserId, std::vector<data::ChatRoomInfo>& rooms);
    int getRooms(std::vector<data::ChatRoomInfo>& rooms);
    bool registerUser(data::UserInfo& user, data::Account& account);
    int searchAutor(std::string text, std::vector<data::UserInfo>& users);
    int searchGroup(std::string text, std::vector<data::ChatRoomInfo>& grups);

    
    void addFriends(std::string userid, std::string friendsId);
    void delFriends(std::string userid, std::string friendsId);
};

#endif